<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use EasyWeChat;
use App\Models\User;

class FrontAuthMiddleware {

    /**
     * Run the request filter.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {   
        if(auth()->guard($guard)->guest()) {
            $officialAccount = EasyWeChat::officialAccount();
            $wxOauth = session('wechat.oauth_user.default'); // 拿到授权用户资料
            $wxUser = $officialAccount->user->get($wxOauth->token->openid); // 微信用户信息
            
            $user = User::where('openid', $wxUser['openid'])->first();
            if($user) {
                // 存在用户
                $user->name = $wxUser['nickname'];
                $user->avatar = $wxUser['headimgurl'];
                $user->info = $wxUser;
                // $user->loginip = '';
                $user->save();
            }else {
                if(!$wxUser['subscribe']) {
                    echo "如果没关注，那么跳转到关注二维码";
                    exit();
                }

                $user = new User;
                $user->name = $wxUser['nickname'];
                $user->avatar = $wxUser['headimgurl'];
                $user->openid = $wxUser['openid'];
                $user->password = bcrypt('131525');
                $user->info = $wxUser;
                $user->save();
                
                $user = User::where('openid', $wxUser['openid'])->first();
            }

            Auth::login($user);
        }

        return $next($request);
    }

}